﻿using System;
using System.Data.Entity;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Portal.Model;
using Rhino.Mocks;

namespace Portal.Repository.Tests.System
{
	[TestClass()]
	public class UserRepositoryTests : PortalTests
	{
		#region GetBy
		[TestMethod()]
		public void GetUserBy_UserExists_ReturnsUser()
		{
			var login = Guid.NewGuid().ToString();
			Entities.User.Add(
				new User()
				{
					Login = login
				}
			);
			Entities.SaveChanges();

			var repository = GetRepository();
			var result = repository.GetBy(login);
			Assert.IsNotNull(result);
		}

		[TestMethod()]
		public void GetUserBy_UserDoesNotExist_ReturnsNull()
		{
			var login = Guid.NewGuid().ToString();
			var repository = GetRepository();
			var result = repository.GetBy(login);
			Assert.IsNull(result);
		}

		[TestMethod()]
		public void GetUserBy_LoginIsNull_ReturnsNull()
		{
			var repository = GetRepository();
			var result = repository.GetBy(null);
			Assert.IsNull(result);
		}

		#endregion

		#region Insert

		[TestMethod()]
		public void AddOrUpdate_UserIsNull_ReturnsNull()
		{
			var repository = GetRepository();
			var result = repository.AddOrUpdate(null);
			Assert.IsNull(result);
		}

		[TestMethod()]
		public void AddOrUpdate_UserExists_UserUpdated()
		{
			var login = Guid.NewGuid().ToString();

			var user = Mocks.DynamicMock<IUser>();
			user.Expect(x => x.Login).Return(login);
			user.Expect(x => x.Id).Return(123);
			user.LastName = "last name";
			user.FirstName = "first name";
					
			Mocks.ReplayAll();
			
			Entities.User.Add(
				new User()
				{
					Login = login,
					FirstName = "first",
					LastName = "last"
				}
			);
			Entities.SaveChanges();

			var repository = GetRepository();
			var result = repository.AddOrUpdate(user);
			Assert.IsNotNull(result);
			Assert.AreEqual(user.LastName, result.LastName);
			Assert.AreEqual(user.FirstName, result.FirstName);

		}

		[TestMethod()]
		public void AddOrUpdate_UserDoesNotExist_UserInserted()
		{
			var login = Guid.NewGuid().ToString();

			var user = Mocks.DynamicMock<IUser>();
			user.Expect(x => x.Login).Return(login);
			user.Expect(x => x.Id).Return(123);
			user.LastName = "last name";
			user.FirstName = "first name";

			Mocks.ReplayAll();

			var repository = GetRepository();
			var result = repository.AddOrUpdate(user);
			Assert.IsNotNull(result);
			Assert.AreEqual(user.LastName, result.LastName);
			Assert.AreEqual(user.FirstName, result.FirstName);
		}
		
		#endregion

		private IUserRepository GetRepository()
		{
			return new UserRepository(Entities);
		}
	}
}